﻿using CoilIntelStorage.Models;
using CoilIntelStorage.Utils;
using CoilIntelStorage.ViewModels;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace CoilIntelStorage
{
    public class ValueSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            DataTemplate dt = new DataTemplate();
            if (item != null && item is TaskQueue)
            {
                TaskQueue model = item as TaskQueue;
                Window window = Application.Current.MainWindow;
                if (model.OrderNo == 1)
                {
                    //实例化文本控件
                    FrameworkElementFactory label = new FrameworkElementFactory(typeof(Label));
                    label.SetBinding(Label.ContentProperty, new Binding()
                    {
                        Path = new PropertyPath("Id"),
                        Mode = BindingMode.TwoWay,
                        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                    });
                    label.SetValue(Label.MarginProperty, new Thickness(2));
                    label.SetValue(Label.ForegroundProperty, Brushes.Red);
                    label.SetValue(Label.FontSizeProperty, 20d);
                    label.SetValue(Label.ContentProperty, "正在执行");
                    dt.VisualTree = label;

                }
                else if (model.OrderNo != 1)
                {
                    //实例化按钮控件
                    FrameworkElementFactory button = new FrameworkElementFactory(typeof(Button));
                    button.SetBinding(Button.TagProperty, new Binding()
                    {
                        Path = new PropertyPath("Id"),
                        Mode = BindingMode.TwoWay,
                        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                    });
                    button.SetValue(Button.ForegroundProperty, Brushes.Black);
                    button.SetValue(Button.HorizontalAlignmentProperty, HorizontalAlignment.Center);
                    button.SetValue(Button.ContentProperty, "取消");
                    button.SetValue(Button.ForegroundProperty, Brushes.White);

                    //添加鼠标左键点击抬起事件
                    button.AddHandler(Button.ClickEvent, new RoutedEventHandler(Button_MouseLeftButtonUpEvent));

                    //button.SetValue(Button.PaddingProperty, new Thickness(5, 0, 0, 0));
                    //button.SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#218aff")));
                    dt.VisualTree = button;
                }
            }
            return dt;
        }

        // 鼠标左键弹起事件
        private void Button_MouseLeftButtonUpEvent(object sender, RoutedEventArgs e)
        {
            Int32 id = Convert.ToInt32(((Button)sender).GetValue(Button.TagProperty));
            String sql = "DELETE task_queue WHERE id = @id;";
            SqlParameter[] sqlParameters = new SqlParameter[] {
                    new SqlParameter("@id",id)};
            int n = DbHelper.ExcuteSQL(sql, sqlParameters);
            if (n > 0)
            {
                //寻找父窗体
                Window window = GetParentObject<Window>(((Button)sender), "MainWin");
                //执行父窗体的刷新任务队列的命令
                var MyVM = window.DataContext as MainWindowViewModel;
                if (MyVM != null && MyVM.RefreshCommandListCommand.CanExecute()) {
                    MyVM.RefreshCommandListCommand.Execute();
                }
             
            }
        }
        /// <summary>
        /// 获取父级控件
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="obj">当前控件的Name</param>
        /// <param name="name">要查找的父级控件的Name（Name为“ ”时，表示上一次父控件）</param>
        /// <returns></returns>
        public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);
            while (parent != null)
            {
                if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)parent;
                }
                parent = VisualTreeHelper.GetParent(parent);
            }
            return null;
        }
        
    }
}
